//
//  AppDelegate.m
//  PDF
//
//  Created by yht on 9/14/14.
//
//

#import "AppDelegate.h"
#import "fpdfview.h"

void BGRA2RGB(unsigned char* pSrc, int sStride, unsigned char* pDest, int nWidth, int nHeight)
{
	int dStride = nWidth * 3;
	unsigned char *srcbuf, *dstbuf;
	
	for (int i = 0; i <nHeight ; i++) {
		
		srcbuf = pSrc + i* sStride;
		dstbuf = pDest + i * dStride;
		
		for (int j = 0; j< sStride; j=j+4, dstbuf+=3, srcbuf+=4) {
			dstbuf [0] = srcbuf [2];
			dstbuf [1] = srcbuf [1];
			dstbuf [2] = srcbuf [0];
		}
	}
}


@implementation AppDelegate


- (CGImageRef)refFromBuffer:(void*)buffer width:(NSInteger)width height:(NSInteger)height
{
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CFDataRef rgbData = CFDataCreate(NULL, (const UInt8*)buffer, width * height * 3);
    
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(rgbData);
    
    CGImageRef rgbImageRef = CGImageCreate(width, height, 8, 24, 3*width, colorspace, kCGBitmapByteOrderDefault, provider, NULL, true, kCGRenderingIntentDefault);
    
    CFRelease(rgbData);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorspace);
    
    // use the created CGImage
    return rgbImageRef;
}


- (NSImage*)imageFromCGImageRef:(CGImageRef)image
{
    NSImage* newImage = nil;
    
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
    NSBitmapImageRep*    newRep = [[NSBitmapImageRep alloc] initWithCGImage:image];
    NSSize imageSize;
    
    // Get the image dimensions.
    imageSize.height = CGImageGetHeight(image);
    imageSize.width = CGImageGetWidth(image);
    
    newImage = [[NSImage alloc] initWithSize:imageSize];
    [newImage addRepresentation:newRep];
    
#else
    
    NSRect imageRect = NSMakeRect(0.0, 0.0, 0.0, 0.0);
    CGContextRef imageContext = nil;
    
    // Get the image dimensions.
    imageRect.size.height = CGImageGetHeight(image);
    imageRect.size.width = CGImageGetWidth(image);
    
    // Create a new image to receive the Quartz image data.
    newImage = [[NSImage alloc] initWithSize:imageRect.size];
    [newImage lockFocus];
    
    // Get the Quartz context and draw.
    imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
    CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
    [newImage unlockFocus];
    
#endif
    
    return newImage;
}


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
}

- (IBAction)openDocument:(id)sender
{
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setDirectory:NSHomeDirectory()];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:YES];
    [panel setAllowedFileTypes:@[@"pdf"]];
    [panel setAllowsOtherFileTypes:YES];
    if ([panel runModal] == NSOKButton) {
         NSString *path = [panel.URLs.firstObject path];
          //code
        [self openFileAndDisplay:path];
      }
}

- (void)openFileAndDisplay:(NSString*)path
{
    // Insert code here to initialize your application
    FPDF_InitLibrary(NULL);
    
    FPDF_DOCUMENT	doc = FPDF_LoadDocument([path UTF8String],
                                            NULL);
    //int pageCount = FPDF_GetPageCount(doc);
    
    FPDF_PAGE	page = FPDF_LoadPage(doc, 21);
    int pdfWidth = FPDF_GetPageWidth(page);
    int pdfHeight = FPDF_GetPageHeight(page);
    
    int viewWidth = 400;
    int viewHeight = 400;
    
    
    FPDF_BITMAP bitmap = FPDFBitmap_Create(viewHeight, viewHeight, 0);
    void *buf = FPDFBitmap_GetBuffer(bitmap);
    int stride = FPDFBitmap_GetStride(bitmap);
    memset(buf, -1, stride*viewHeight);
    FPDF_RenderPageBitmap(bitmap, page, 0, 0,
                          pdfWidth, pdfHeight, 0, 0);
    
    
    void *dst = malloc(viewWidth*viewHeight*3);
    memset(dst, -1, viewWidth*viewHeight*3);
    BGRA2RGB((unsigned char *)buf, stride, (unsigned char *)dst, viewWidth, viewHeight);
    
    CGImageRef imgRef = [self refFromBuffer:dst width:viewWidth height:viewHeight];
    NSImage *image = [self imageFromCGImageRef:imgRef];
    CFRelease(imgRef);
    self.imageView.image = image;
    
    free(buf);
    free(dst);
    FPDF_ClosePage(page);
    FPDF_CloseDocument(doc);
    FPDF_DestroyLibrary();
}

@end
